s = [i for i in xrange(10, 0, -1)]

from itertools import *

print s
ansList = []
for p in permutations(s, 10):
    s1 = p[0] + p[1] + p[2]
    s2 = p[2] + p[3] + p[4]
    s3 = p[4] + p[5] + p[6]
    s4 = p[6] + p[7] + p[8]
    s5 = p[1] + p[8] + p[9]

    if s1 == s2 and s2 == s3 and s3 == s4 and s4 == s5:
        ans = [[p[0] , p[1] , p[2]] , [p[3] , p[2] , p[4]] , [p[5] , p[4] , p[6]] , [p[7] , p[6] , p[8]] , [p[9] , p[8] , p[1]]]
        maxIdx, minN = 0, ans[0][0]
        for i in xrange(len(ans)):
            if ans[i][0] < minN:
                maxIdx, minN = i, ans[i][0]
        ss = ''
        for i in xrange(maxIdx, len(ans)):
            ss = ss + ''.join([str(n) for n in ans[i]])
        for i in xrange(maxIdx):
            ss = ss + ''.join([str(n) for n in ans[i]])
        if len(ss) == 16:
            ansList.append(ss)

ansList.sort()
print ansList[-1]


